import Ember from 'ember';
const {callStatus_calling,callStatus_inCall,callStatus_callWait,callStatus_callFailure,callStatus_callLost,callStatus_callEnd,taskApplyStatus_apply,taskApplyStatus_applySuc,action_sign} = Constants;
export default Ember.Controller.extend({
  moment: Ember.inject.service(),
  pathConfiger: Ember.inject.service("path-configer"),
  service_PageConstrut:Ember.inject.service("page-constructure"),
  service_notification:Ember.inject.service("notification"),
  dateService: Ember.inject.service('date-service'),
  busipageTitle: null,
  //皮肤列表
  themes:Ember.computed(function(){
    var data = [{
      code:"elegance",
      title:"雅致",
      hasSelected: true,
    },{
      code:"fresh",
      title:"清新",
      hasSelected: false,
    },{
      code:"warmth",
      title:"热情",
      hasSelected: false,
    }];
    var arr = Ember.A();
    data.forEach(function(item){
      var ent = Ember.Object.create(item);
      ent.reopen({
        titleWhole:Ember.computed("title","hasSelected",function(){
          if(this.hasSelected){
            return this.get("title") + "(当前)";
          }
          return this.get("title");
        }),
      });
      arr.pushObject(ent);
    });
    return arr;
  }),
  showPopPasschangeModal:false,
  showDialogModal:false,
  showImageCropper:false,
  topTipAnimationClass: "elementToFadeInAndOut",
  curRouteName:null,//当前子页面route名称

  init: function () {
    this.get("service_PageConstrut").set("mainpageController",this);
    var _self = this;
    Ember.run.schedule("afterRender",this,function() {
      //放入页面标题
      var title =$("h1[name='busipage-title']");
      console.log("breadcrumb-env:",$(".breadcrumb-env").get(0));
      //提示弹窗
      $("#pop-tip").on("webkitAnimationEnd",function(){
        console.log("webkitAnimationEnd in");
        $(this).removeClass(_self.get("topTipAnimationClass"));
        $(this).hide();
      });
      //默认皮肤
      _self.send("changeTheme","elegance");
      $(".img-responsive").click(function(){
        _self.showPopTip("testtest");
      });
    });
  },
  actions:{
    typeAge:function(value){//年龄设置
      this.set('saveCustomerInfoSuccess',false);
      this.set('saveCustomerInfoFail',false);
      this.set('customer.age',value);
    },
    sexSelect:function(value) {
      this.set('saveCustomerInfoSuccess',false);
      this.set('saveCustomerInfoFail',false);
      this.set('customer.sex',value);
    },
    popPerfect(params){
      console.log("popPerfect in,params",params);
      $scrollbar.perfectScrollbar('update');
    },
    //统一切换页面调用
    transPage(item){
      console.log("item in",item);
      //前缀都是business.mainpage
      var routePath = "business.mainpage." + item.url;
      console.log("routePath:" + routePath);
			this.switchMainPage(item.url);
    },
    //弹出修改密码页面
    popChangePass: function(){
      this.set("showPopPasschangeModal",true);
    },
    cancelPassSubmit: function(){
      this.set("showPopPasschangeModal",false);
      this.set('password','');
      this.set('newPass','');
      this.set('confirmPass','');
      this.set("responseInfo","");
    },
    changeInfo: function(){
      this.set("responseInfo",'');
    },
    //换肤
    changeTheme: function(themeCode){
      this.get("themes").forEach(function(theme){
        if(theme.get("code")===themeCode){
          theme.set("hasSelected",true);
          $("html").attr("class",theme.get("code"));
        }else{
          theme.set("hasSelected",false);
        }
      });
    },
    //退出登录
    quit: function(){
      var curUser = this.get("global_curStatus").getUser();
      var role = curUser.get('role').get('id');
      console.log("curUser role in quit:" + role);
      //全部清空
      localStorage.clear();
      //清除socket登录状态
      this.get("service_notification").set("hasLogin",false);
      var link = "user-login";
      var params = {};
      if(parseInt(role) === 1) {
        params = {queryParams:{loginType:1}};
      }
      if(parseInt(role) === 2) {
        params = {queryParams:{loginType:2}};
      }
      //手机端直接跳转到首页面
      if(this.get("global_curStatus").get("isMobile")){
        this.get("global_curStatus").toIndexPage();
        return;
      }
      console.log("need to login,params",params);
      this.transitionToRoute(link,params);
    },
    //修改密码确认
    changePassSubmit: function(){
      var curUser = this.get("global_curStatus").getUser();
      var _self = this;
      var psd = this.get('password');
      var newPsd = this.get('newPass');
      var confirmPsd = this.get('confirmPass');
      if(!psd) {
        this.set("responseInfo","请输入旧密码！");
      }
      else if (!newPsd) {
        this.set("responseInfo","请输入新密码！");
      }
      else if (!confirmPsd) {
        this.set("responseInfo","请输入确认密码！");
      }
      else {
        if(!newPsd.match(/^.{6,}$/)) {
          this.set("responseInfo","新密码格式不正确,请输入6位以上字符！");
        }
        else if(newPsd!==confirmPsd) {
          this.set("responseInfo","确认密码与新密码不一致！");
        }
        else {
          var user = this.store.createRecord('userSession',{});
          user.set('id',curUser.get('id'));
          user.set('password',$.md5(psd));
          user.set('newPassword',$.md5(newPsd));
          this.get("global_ajaxCall").set("action","modifyPassword");
          user.save().then(function(userData) {
            if(userData.get('errcode')===0) {
              _self.set('responseInfo','旧密码输入错误！');
            }
            else {
              _self.store.query('localstorage/user',curUser.get('loginName')).then(function(users) {
                var user = users.get('firstObject');
                user.set('password',$.md5(newPsd));
                user.save().then(function() {
                  _self.set("showPopPasschangeModal",false);
                  _self.set('password','');
                  _self.set('newPass','');
                  _self.set('confirmPass','');
                  _self.set("responseInfo","");
                  alert('密码修改成功！');
                });
              });
            }
          },function() {
            alert('密码修改失败！');
          });
        }
      }
    },
    confirmDialog: function(){
      this.set("showDialogModal",false);
      var confirmAction = this.get("dialogConfirmAction");
      if(confirmAction){
        confirmAction();
      }
    },
    closeDialog: function(){
      this.set("showDialogModal",false);
    },
    showPopTip(msg){
      this.refreshPage();
      // this.showPopTip(msg);
    },
    //关闭图片上传窗口
    cancelImageCropper: function(){
      this.set("showImageCropper",false);
    },
    imageCropperOpened(){
      console.log("need cropit:",$('#image-cropper'));
      //弹窗打开后进行组件初始化
      $('#image-cropper').cropit({
            exportZoom: 2,
            imageBackground: true,
            onFileChange: function(){
              let imgDom = $('#image-cropper .cropit-preview-image-container');
              imgDom.find("img").hide();
              imgDom.find("img").removeClass("defaultBackImg");
              // imgDom.find("img").remove();
              imgDom.find(".backTip").remove();
            },
            onImageLoaded: function(){
              let imgDom = $('#image-cropper .cropit-preview-image-container');
              imgDom.find("img").show();
            }
      });
      let imgDom = $('#image-cropper .cropit-preview-image-container');
      console.log("imgDom",imgDom);
      //设置背景图片和提示
      imgDom.find("img").attr("src",this.get("pathConfiger").getIconLocalPath('image-file.png'));
      imgDom.find("img").addClass("defaultBackImg");
      imgDom.append("<div class='backTip'>您需要首先选择图片文件</div>");
      //设置功能按钮
      $('.rotation-btns .fa-rotate-left').click(function() {
        $('#image-cropper').cropit('rotateCW');
      });
      $('.rotation-btns .fa-repeat').click(function() {
        $('#image-cropper').cropit('rotateCCW');
      });
    },
    //图片编辑的图片选择功能
    chooseImage(){
      $('.cropit-image-input').click();
    },
    //图片编辑完毕
    cropImgOk(){
      let imageData = $('#image-cropper').cropit('export');
      let fileData = $('#image-cropper input.cropit-image-input');
      console.log("fileData is",fileData);
      var filename = fileData.val().split('\\').pop();
      //关闭弹窗
      this.set("showImageCropper",false);
      //获得之前预存的回调函数，并放入图片数据
      let callback = this.get("imgCropCallback");
      callback(imageData,filename);
    }
  },

  /***************************导航及页面跳转部分******************/
  needs: ["application"],
  breadCrumbsPath: null,//当前路径
  breadCrumbsList: [],//导航树历史路径

  //根据当前路径，计算导航信息
  breadCrumbsMoinitor: function () {
    var treeList = this.get("service_PageConstrut").computeBreadCrumbs(this.get('breadCrumbsPath'));
    console.log("treeList in mainpage",treeList);
    this.set("breadCrumbsList",treeList);
  }.observes('breadCrumbsPath'),

  //切换页面
  switchMainPage:function (routeName,params) {
    console.log("switchMainPage in,routeName:" + routeName);
    //取得当前route并记录为原有route
    var curRouteName = this.get("curRouteName");
    this.set("curRouteName",routeName);
    //使用原route进行跟踪功能
    this.get("service_PageConstrut").switchMainPageTrack(routeName,curRouteName,params);
  },
  //刷新页面
  refreshPage:function (routeInst) {
    //刷新页面前，需要设置切换标识
    this.get("service_PageConstrut").incrementProperty("preTransitionFlag");
    //如果routeInst有，则刷新指定页面，否则刷新主页面
    if(routeInst){
      routeInst.refresh();
    }else{
      var mainRoute = App.lookup("route:business.mainpage");
      mainRoute.refresh();
    }
  },
  /***************************弹层及提示相关******************/
  showPopTip:function(msg,showTime,hideTime){
    $("#pop-tip").show();
    $("#pop-tip").html(msg);
    $("#pop-tip").removeClass(this.get("topTipAnimationClass"));
    $("#pop-tip").addClass(this.get("topTipAnimationClass"));
  },
  //显示以后不消失
  openPopTip:function(msg){
    $("#pop-tip").show();
    $("#pop-tip").html(msg);
  },
  closePopTip:function(msg){
    $("#pop-tip").hide();
    // $("#pop-tip").html(msg);
  },
  //confirm窗口
  showConfirm: function(message,confirmAction){
    this.set("showDialogModal",true);
    this.set("dialogMessage",message);
    this.set("dialogConfirmAction",confirmAction);
  },
  //图片编辑窗口,参数
  popImageCropper(callback){
    //预存回调函数
    this.set("imgCropCallback",callback);
    //弹窗
    this.set("showImageCropper",true);
  },
});
